package joke.deal;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;

import joke.ibatis.dao.ComicDao;
import joke.ibatis.po.ComicPO;
import joke.ibatis.po.ParameterPo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DoNewImage {
	public void updateComicMagic(String id) {
		ApplicationContext factory = new ClassPathXmlApplicationContext(
				"applicationContext.xml");// 初始化配置文件
		ParameterPo parpo = new ParameterPo();
		parpo.setId(id);

		ComicDao cdao = (ComicDao) factory.getBean("comicDao");// 获取pageLinkDao对象
		List contentList = cdao.getComics(parpo);
		for (int i = 0; i < contentList.size(); i++) {
			System.out.println(contentList.size());
			ComicPO po = (ComicPO) contentList.get(i);
			System.out.println(po.getName());
			InputStream in = new ByteArrayInputStream(po.getMagic());
			BufferedImage image = null;
			NewScaleImage scImage = null;
			try {
				image = javax.imageio.ImageIO.read(in);
				scImage = new NewScaleImage(image, po.getName());
				BufferedImage phoneImage = scImage.scaleImage(480);
				byte[] phoneb = imageToBytes(phoneImage, "jpg");
				po.setMagic(phoneb);// 适合手机上的图
				cdao.updateComic(po);
				System.out.println("-----------------"+po.getId());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static byte[] imageToBytes(BufferedImage bImage, String format) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ImageIO.write(bImage, format, baos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] bytesOut = baos.toByteArray();
		return bytesOut;
	}
}
